const Img64 = require('../file/Img64');

class WxLogin {
    constructor(obj) {
        this.code = obj.body.code;
        this.userInfo = obj.body.userInfo;
    }

    check() {
        if (!this.code) {
            return { success: false, msg: '临时凭证为空' };
        }
        if (this.userInfo) {
            let nickName = this.userInfo.nickName || '微信用户';   // 用户名
            let avatarUrl = this.userInfo.avatarUrl || '';        // 头像
            let gender = this.userInfo.gender || '未知';          // 性别
            if (nickName.length > 50) {
                return { success: false, msg: '用户名过长' };
            }
            if (gender !== '男' && gender !== '女' && gender !== '未知') {
                return { success: false, msg: '性别错误' };
            }
            if (avatarUrl) {
                let img64 = new Img64({ img: avatarUrl });
                // 判断参数是否合法
                let flag = img64.check();
                if (!flag.success) {
                    return flag;
                }
                this.userInfo.avatarBuffer = img64.buffer;
            }
        } else {
            this.userInfo = {};
            this.userInfo.nickName = '微信用户';
            this.userInfo.gender = '未知';
            this.userInfo.avatarUrl = '';
            this.userInfo.avatarBuffer = null;
        }
        return { success: true };
    }
}

module.exports = WxLogin;